package com.hsd.netty.client.handler;

import com.hsd.netty.client.common.NettyHeader;
import com.hsd.netty.client.common.NettyMessage;
import com.hsd.netty.client.enums.MessageCode;
import com.hsd.netty.client.enums.MessageType;
import com.hsd.netty.client.strategy.NettyMessageExecutor;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author s.he
 * on 2020/6/6
 */
@Service
@ChannelHandler.Sharable
public class LoginAuthRequestHandler  extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(LoginAuthRequestHandler.class);

    @Autowired
    private NettyMessageExecutor nettyMessageExecutor;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        ctx.writeAndFlush(buildLoginRequest());
        logger.info("【登录请求】netty测试客户端 : 发送登录信息");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        NettyMessage nettyMessage = (NettyMessage)msg;
        NettyHeader nettyHeader = nettyMessage.getNettyHeader();
        byte type = nettyHeader.getType();
        MessageType messageType = MessageType.getMessageType(type);
        nettyMessageExecutor.execute(messageType, ctx, nettyMessage);

        /**
         * 登录成功之后发送数据
         */
        if(messageType.equals(MessageType.LOGIN) && nettyHeader.getStatusCode().equals(MessageCode.SUCCESS.getCode())) {
            ctx.fireChannelRead(msg);
        }

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        ctx.close();
    }

    public NettyMessage buildLoginRequest() {
        NettyMessage nettyMessage = new NettyMessage();
        NettyHeader header = new NettyHeader();
        header.setType(MessageType.LOGIN.getCode());
        nettyMessage.setNettyHeader(header);
        return nettyMessage;
    }
}
